
import Taro from '@tarojs/taro'

let preState = {}
let cacheExincludeKeys = new Set(["@@dva", "loading", "temp", "tabbar"]);//排除不缓存的state值


export const writeCache = (state) => {

    let keys = Object.keys(state)
    let cacheState = {}

    for (const key of keys) {
        if (cacheExincludeKeys.has(key)) {
            continue
        }

        if (!preState) {
            cacheState[key] = state[key]
            continue
        }

        if (!preState.hasOwnProperty(key)) {
            cacheState[key] = state[key]
            continue
        }

        if (JSON.stringify(preState[key]) != JSON.stringify(state[key])) {
            cacheState[key] = state[key]
        }
    }
    preState = state

    if (Object.keys(cacheState).length <= 0) {
        return
    }

    console.log("保存state", cacheState)
    let preCache = Taro.getStorageSync("state")

    let mergeCache
    if (preCache.length <= 0) {
        mergeCache = cacheState
    } else {
        mergeCache = Object.assign(preCache, cacheState)
    }

    Taro.setStorageSync("state", mergeCache)
}

export const readCache = () => {
    let cache = Taro.getStorageSync("state")
    if (cache.length <= 0) {
        return null
    }
    preState = cache
    console.log(preState)
    return cache
}
